import { service } from "../api/config";
import { showSuccessToast, showFailToast } from "vant";
import router from "../router";

export const IShoppingDetails = async (url, data) => {
  const { data: result } = await service.get(url, data);
  return result.data;
};

export const IComment = async (url, data) => {
  const { data: result } = await service.get(url, data);
  return result.data;
};

export const ILogin = async (url, data) => {
  const { data: result } = await service.post(url, data);
  const { errno, errmsg, data: info } = result;
  if (errno === 700) {
    showFailToast(errmsg);
  } else {
    showSuccessToast("登录成功");
    localStorage.setItem("token", info.token);
    localStorage.setItem("userInfo", JSON.stringify(info));
    router.push("/");
  }
};

export const IRegister = async (url, data) => {
  const { data: result } = await service.post(url, data);
  if (result.errmsg == "成功") {
    showSuccessToast(result.errmsg);
    localStorage.setItem("userInfo", JSON.stringify(result.data.userInfo));
    router.push("/login");
  } else {
    showFailToast(result.errmsg);
  }
};

export function fetchData(title, pages, value) {
  const paramss = {
    // 请求参数
    type: 0,
    status: title,
    page: pages,
    limit: 10,
  };
  const day = new Date();
  let promises = [];
  const comments = []; // 将数组初始化移到外部
  return new Promise((resolve, reject) => {
    service
      .get("/wx/coupon/mylist", { params: paramss })
      .then((res) => {
        comments.push(...res.data.data.list);
        for (let i = 2; i <= res.data.data.pages; i++) {
          paramss.page = i;
          const promise = service.get("/wx/coupon/mylist", { params: paramss });
          promises.push(promise);
        }
        Promise.all(promises)
          .then((res) => {
            res.forEach((item) => {
              comments.push(...item.data.data.list);
            });
            comments.forEach((item) => {
              const day2 = new Date(item.endTime);
              const timeDiff = day2.getTime() - day.getTime();
              const dayDiff = Math.floor(timeDiff / (1000 * 3600 * 24));
              item.endTime = dayDiff;
            });
            console.log(value);
            if (value != 0) {
              const arr = comments.filter(
                (res) => res.min < value && res.endTime > 0
              );
              resolve(arr);
            }
            resolve(comments);
          })
          .catch((error) => {
            reject(error);
          });
      })
      .catch((error) => {
        reject(error);
      });
  });
}
